/*
 * Copyright 2011 Stefan Ferstl
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.google.code.debmavenplugin.archiver;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Set;

import org.apache.commons.compress.archivers.ArchiveOutputStream;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;


/**
 * Abstract implementation that packs {@link IFileArchiveEntry} objects into an
 * archive. Subclasses need to implement the method
 * {@link #createFileFilter(ArchiveMetaData)} to get the files to be packed and
 * the method {@link #createArchiveOutputStream(File)} to create the appropriate
 * archive output stream to send the files to.
 */
public abstract class AbstractArchiver<E extends IFileArchiveEntry> {

  private File target;
  private ArchiveMetaData metaData;

  /**
   * Constructor.
   *
   * @param target The target file of this archiver.
   * @param metaData The metadata of the archive to be created.
   */
  public AbstractArchiver(File target, ArchiveMetaData metaData) {
    this.target = target;
    this.metaData = metaData;
  }

  /**
   * Packs the collected archive entries into the archive.
   *
   * @throws IOException In case something goes wrong.
   */
  public void createArchive() throws IOException {
    ArchiveOutputStream arOs = createArchiveOutputStream(this.target);

    try {
      AbstractCollectingFileFilter<E> collectingFileFilter = createFileFilter(this.metaData);

      FileUtils.listFiles(this.metaData.getBaseDirectory(), collectingFileFilter, collectingFileFilter);
      Set<E> fileCollection = collectingFileFilter.getCollectedFiles();
      for (E entry : fileCollection) {
        addToArchive(entry, arOs);
      }
    } finally {
      IOUtils.closeQuietly(arOs);
    }
  }

  /**
   * Creates a file filter to collect the archive entries to be packed.
   *
   * @param metaData Metadata defining the archive to be created.
   * @return The created file filter.
   */
  protected abstract AbstractCollectingFileFilter<E> createFileFilter(ArchiveMetaData metaData);

  /**
   * Creates the archive output stream to which the collected archive entries
   * should be written.
   *
   * @param file Target of the archive output stream.
   * @return The created archive output stream.
   * @throws IOException In case something goes wrong during stream creatioin.
   */
  protected abstract ArchiveOutputStream createArchiveOutputStream(File file) throws IOException;

  /**
   * Returns the metadata for the archive that should be created. To be used by subclasses.
   * @return The metadata of the archive to be created.
   */
  protected ArchiveMetaData getMetaData() {
    return this.metaData;
  }


  /**
   * Writes an archive entry to the archive output stream.
   *
   * @param archiveEntry The archive entry to be written.
   * @param archiveOutputStream The archive output stream to which the entry
   * should be written
   * @throws IOException In case something goes wrong when writing the archive
   * entry.
   */
  private void addToArchive(E archiveEntry, ArchiveOutputStream archiveOutputStream) throws IOException {
    archiveOutputStream.putArchiveEntry(archiveEntry);

    FileInputStream fis = null;
    try {
      if (!archiveEntry.isDirectory()) {

        fis = new FileInputStream(archiveEntry.getFile());
        IOUtils.copy(fis, archiveOutputStream);
      }
      archiveOutputStream.closeArchiveEntry();
    } catch (IOException e) {
      IOUtils.closeQuietly(fis);
      throw new IOException("An error occurred while adding archive entry '"
          + archiveEntry.getName() + "' to archive.", e);
    }
  }

}
